import React from 'react';
import { Button, Form, Input, InputNumber } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { IMetaFormProps, MetadataFormContext } from '../interface';
import { useGetExtraInfo } from '../hooks';

function Index(props: IMetaFormProps) {
  const { id, require, items } = props;
  const formContext: any = React.useContext(MetadataFormContext) || {};
  const extraInfo = useGetExtraInfo(formContext.fields, id, formContext.form);

  return (
    <>
      <div className="ant-form-item-label">
        <label className={`${require && 'ant-form-item-required'}`}>{extraInfo.label || id}</label>
      </div>
      <div style={{ padding: '10px', border: '1px solid #d9d9d9', width: '100%', borderRadius: '4px' }}>
        <Form.List name={id}>
          {(fields, { add, remove }) => (
            <>
              {fields.map((field) => (
                <div key={field.key} style={{ display: 'flex', marginBottom: '10px' }}>
                  <>
                    <Form.Item
                      {...field}
                      style={{ flex: 1, paddingRight: '10px' }}
                      name={[field.name]}
                      fieldKey={[field.fieldKey]}
                      rules={[{ required: true, message: `请输入${extraInfo.label}` }]}
                    >
                      {items?.type === 'text' && <Input />}
                      {items?.type === 'number' && <InputNumber />}
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                  </>
                </div>
              ))}
              <Form.Item>
                <Button type="dashed" onClick={() => add()} icon={<PlusOutlined />}>
                  添加
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </div>
    </>
  );
}

export default React.memo(Index);
